package com.jiyinit.web.core.business.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.UserTaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.DateUtil;
import com.jiyinit.web.core.common.util.UserUtil;

/**
 * 用户管理
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/userTask")
public class UserTaskController {
	/**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
    
    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskServiceImpl;
    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;
    
    
    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param
     * @return
     */
   
    @RequestMapping(method = RequestMethod.POST, value = "/anon/findUserTasks")
    @ResponseBody
    public PagingResult<UserTaskVo> findByPage(HttpServletRequest request, UserTaskRequest userTaskRequest) {
    	userTaskRequest.setLimit(10);
        PagingResult<UserTaskVo> pagingResult = userTaskServiceImpl.findUserTasksByTaskId(userTaskRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }
    
   
    
    
    /**
     * 新增任务
     *
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addUserTask")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request, UserTaskRequest userTaskRequest) {
    	// 校验参数
        ValidateResult<UserTaskRequest> validateResult = paramCheckLogic.checkParamValidate(userTaskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
        BeanUtils.copyProperties(userTaskRequest, tabCoreUserTask);
        
        Integer[] userIdss = userTaskRequest.getAlloterIds();
       
	  	int num = 0;
	  	num = userTaskServiceImpl.addTaskAndUser(userIdss,userTaskRequest.getTaskId());
	     if (num > 0) {
	         return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
	     }
	     return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        // 校验参数
//    	Double plDays = 0.0;
//        ValidateResult<UserTaskRequest> validateResult = paramCheckLogic.checkParamValidate(userTaskRequest);
//        if (!validateResult.isSuccess()) {
//            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
//        }
//        DateUtil std = new DateUtil();
//        TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
//        BeanUtils.copyProperties(userTaskRequest, tabCoreUserTask);
//        Date startTime = tabCoreUserTask.getStartTimePl();
//        Date endTime = tabCoreUserTask.getEndTimePl();
//        try {
//			plDays = (double)std.daysBetween(startTime,endTime);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//        tabCoreUserTask.setPlDays(plDays+1);
//        tabCoreUserTask.setCreateTime(new Date());
//        tabCoreUserTask.setUserId(UserUtil.getCurrentUser().getUserId());
//        
//        int num = userTaskServiceImpl.addUserTask(tabCoreUserTask);
//        if (num > 0) {
//            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
//        }
//        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 下午6:03:57
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updateUserTask")
    public ResponseEntity<ResponseDto> updateUserTask(HttpServletRequest request, UserTaskRequest userTaskRequest) {
        // 校验参数
    	Double plDays = 0.0;
        ValidateResult<UserTaskRequest> validateResult = paramCheckLogic.checkParamValidate(userTaskRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        DateUtil std = new DateUtil();
        TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
        BeanUtils.copyProperties(userTaskRequest, tabCoreUserTask);
        
        Date startTimeReal = tabCoreUserTask.getStartTimeReal();
        Date endTimeReal = tabCoreUserTask.getEndTimeReal();
        double realDays = 0.0;
        if(startTimeReal !=null && endTimeReal !=null){
        	try {
        		realDays = (double)std.daysBetween(startTimeReal,endTimeReal);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
        	tabCoreUserTask.setRealDays(realDays+1);
        }
        tabCoreUserTask.setModifyTime(new Date());
        int num = userTaskServiceImpl.updateUserTask(tabCoreUserTask);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:49:23
         * @param 
         * @return
     */
    @RequestMapping("/userTaskLists")
    public String userTasks(HttpServletRequest request, Integer taskId) {
    	request.setAttribute("taskId", taskId);
    	request.setAttribute("alloterId", UserUtil.getCurrentUser().getUserId());
        return "/tasktouser/taskusers";
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月4日 上午9:01:17
         * @param 
         * @return
     */
    @RequestMapping("/update")
    public String update(HttpServletRequest request, Integer userTaskId) {
    	UserTaskVo userTaskVo = null;
    	userTaskVo = userTaskServiceImpl.findUserTaskById(userTaskId);
    	request.setAttribute("userTaskVo", userTaskVo);
            return "/tasktouser/taskAllotEdit";
    }

   
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月11日 上午11:00:10
         * @param 
         * @return
     */
    @RequestMapping("/fish")
    public String fish(HttpServletRequest request, UserTaskRequest userTaskRequest){
    	List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
    	userTaskVos = userTaskServiceImpl.finAll(userTaskRequest);
    	
    	JSONArray json = new JSONArray();
    	DateUtil std = new DateUtil();
    	for(UserTaskVo userTaskVo : userTaskVos){
            JSONObject jo = new JSONObject();
            
            String startPl = userTaskVo.getStartTimePl()==null?"-":std.getFormatDateToString(userTaskVo.getStartTimePl(),"yyyy/MM/dd");
            String endPl = userTaskVo.getEndTimePl()==null?"-":std.getFormatDateToString(userTaskVo.getEndTimePl(),"yyyy/MM/dd");
            String pl = startPl+"至"+startPl;
            String startReal = userTaskVo.getStartTimeReal()==null?"-":std.getFormatDateToString(userTaskVo.getStartTimeReal(),"yyyy/MM/dd");
            String endReal = userTaskVo.getEndTimeReal()==null?"-":std.getFormatDateToString(userTaskVo.getEndTimeReal(),"yyyy/MM/dd");
            String real = startReal+"至"+endReal;
            
            jo.put("任务实际天数", userTaskVo.getRealDays()==null?0:userTaskVo.getRealDays());
            
            jo.put("任务实际周期", real);
            
            jo.put("任务计划天数", userTaskVo.getPlDays());
            
            jo.put("任务计划周期", pl);
            
            jo.put("任务分配时间", std.getFormatDateToString(userTaskVo.getCreateTime(),"yyyy/MM/dd hh:mm:ss"));
            
            jo.put("受理人", userTaskVo.getUserName());
            
            json.add(jo);
        }
    	request.setAttribute("dataList", json);
        return "/tasktouser/fish";
    }
    
   
}
